package com.zhiwang.planet.work

import android.content.Context
import android.os.Environment
import androidx.work.Data
import androidx.work.Worker
import androidx.work.WorkerParameters
import okhttp3.*
import okio.Okio
import okio.buffer
import okio.sink
import okio.source
import java.io.File
import java.io.IOException

class ApkUpdateDownLoadWork(context: Context, workerParams: WorkerParameters) :

        Worker(context, workerParams) {
    val TAG = "ApkUpdateDownLoadWork"
    override fun doWork(): Result {

        val apkFile = File(Environment.getExternalStorageDirectory().toString() + "/download/planet.apk")

        val okClient = OkHttpClient()

        val url = inputData.getString("apk_file_url") ?: ""

        var failOutputData = Data.EMPTY
        if (url.isEmpty()) return Result.failure(
                Data.Builder()
                        .putString("failure_reason", "apk file url is empty")
                        .build())

        val request = Request.Builder()
                .url(url)
                .build()

        var isOk = false

        okClient.newCall(request)
                .enqueue(object : Callback {

                    override fun onFailure(call: Call, e: IOException) {
                        isOk = false
                    }

                    override fun onResponse(call: Call, response: Response) {
                        val source = response.body()!!.byteStream().source().buffer()
                        val sink = apkFile.sink()
                        source.readAll(sink)
                        sink.close()
                        source.close()
                        isOk = true
                    }
                })


        return if (isOk) Result.success() else Result.retry()
    }
}